/**
 * Copyright 2018 orivil.com. All rights reserved.
 * Use of this source code is governed by a MIT-style
 * license that can be found at https://mit-license.org.
 */

package image

import (
	"time"
	"strconv"
	"path/filepath"
	"os"
)

// 创建新的图片文件及文件夹, 如果 filename 为空, 则按时间创建文件夹
func NewImageFile(filename, ext string) (file *os.File, err error) {
	if filename == "" {
		now := time.Now()
		name := strconv.FormatInt(now.UnixNano(), 10)
		dir := filepath.Join(ImageDir, now.Format("2006/01/02"))
		err = os.MkdirAll(dir, 0777)
		if err != nil {
			return nil, err
		}
		filename = filepath.Join(dir, name+ext)
	} else {
		filename = filename + ext
		dir := filepath.Dir(filename)
		err = os.MkdirAll(dir, 0777)
		if err != nil {
			return nil, err
		}
	}
	return os.OpenFile(filename, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0777)
}